"""
场地模型
"""
from sqlalchemy import Column, String, Float, Integer, Boolean, JSON, DateTime, Enum as SQLEnum
from sqlalchemy.sql import func
from app.core.database import Base
import enum


class VenueType(str, enum.Enum):
    """场地类型"""
    ELEVEN = "11"
    SEVEN = "7"
    FIVE = "5"


class GrassType(str, enum.Enum):
    """草皮类型"""
    NATURAL = "natural"
    ARTIFICIAL = "artificial"


class VenueStatus(str, enum.Enum):
    """场地状态"""
    AVAILABLE = "available"
    BOOKED = "booked"
    MAINTENANCE = "maintenance"


class Venue(Base):
    """场地表"""
    __tablename__ = "venues"
    
    id = Column(String(36), primary_key=True, index=True)
    name = Column(String(200), nullable=False, index=True)
    type = Column(String(100))  # "5人,7人,11人"
    
    # 位置信息（使用数据库中的字段名）
    latitude = Column(Float)  # 纬度
    longitude = Column(Float)  # 经度
    address = Column(String(500), nullable=False)
    city_id = Column(String(100), index=True)
    city_name = Column(String(100), index=True)
    contact_phone = Column(String(20))
    
    # 为了兼容前端，添加属性别名
    @property
    def lat(self):
        return self.latitude
    
    @lat.setter
    def lat(self, value):
        self.latitude = value
    
    @property
    def lng(self):
        return self.longitude
    
    @lng.setter
    def lng(self, value):
        self.longitude = value
    
    # 价格和评分
    price = Column(Float)  # 每2小时价格（可选）
    price_range = Column(String(100))  # 价格区间
    price_note = Column(String(500))  # 价格说明
    rating = Column(Float, default=0.0)
    review_count = Column(Integer, default=0)
    
    # 场地详情
    grass_type = Column(String(50))  # 草皮类型
    facilities = Column(String(500))  # 设施列表，逗号分隔
    images = Column(String(2000))  # 图片URL列表，逗号分隔
    business_hours = Column(String(100))  # "08:00-22:00"
    description = Column(String(1000))  # 场地描述
    
    # 设施（布尔字段）
    has_parking = Column(Boolean, default=False)
    has_shower = Column(Boolean, default=False)
    has_cover = Column(Boolean, default=False)  # 是否有顶棚
    has_light = Column(Boolean, default=False)  # 是否有灯光
    
    # 状态和管理
    status = Column(String(50), default="operating")  # operating, closed, maintenance
    manager_id = Column(String(36))
    
    # 管理后台字段
    creator_type = Column(String(50))  # system, city_manager, venue_manager
    creator_id = Column(String(36))
    city_manager_id = Column(String(36))
    audit_status = Column(String(50), default="approved")  # pending, approved, rejected
    audit_note = Column(String(500))
    audited_by = Column(String(36))
    audited_at = Column(DateTime)
    is_recommended = Column(Boolean, default=False)  # 是否推荐
    sort_order = Column(Integer, default=0)  # 排序
    
    # 统计数据
    view_count = Column(Integer, default=0)
    favorite_count = Column(Integer, default=0)
    
    # 时间戳
    created_at = Column(DateTime, default=func.now())
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
    
    def to_dict(self):
        """转换为字典"""
        # 处理图片和设施字符串转列表
        images = []
        if self.images:
            images = [img.strip() for img in self.images.split(',') if img.strip()]
        
        facilities = []
        if self.facilities:
            facilities = [f.strip() for f in self.facilities.split(',') if f.strip()]
        
        venue_type = []
        if self.type:
            venue_type = [t.strip() for t in self.type.split(',') if t.strip()]
        
        return {
            "id": self.id,
            "name": self.name,
            "type": venue_type,
            "lat": self.lat,
            "lng": self.lng,
            "latitude": self.latitude or self.lat,  # 兼容
            "longitude": self.longitude or self.lng,  # 兼容
            "address": self.address,
            "cityId": self.city_id,
            "cityName": self.city_name,
            "contactPhone": self.contact_phone,
            "price": self.price,
            "priceRange": self.price_range,
            "priceNote": self.price_note,
            "rating": self.rating,
            "reviewCount": self.review_count,
            "grassType": self.grass_type,
            "facilities": facilities,
            "images": images,
            "businessHours": self.business_hours,
            "description": self.description,
            "hasParking": self.has_parking,
            "hasShower": self.has_shower,
            "hasCover": self.has_cover,
            "hasLight": self.has_light,
            "status": self.status,
            "managerId": self.manager_id,
            "creatorType": self.creator_type,
            "creatorId": self.creator_id,
            "cityManagerId": self.city_manager_id,
            "auditStatus": self.audit_status,
            "auditNote": self.audit_note,
            "auditedBy": self.audited_by,
            "auditedAt": self.audited_at.isoformat() if self.audited_at else None,
            "isRecommended": self.is_recommended,
            "sortOrder": self.sort_order,
            "viewCount": self.view_count,
            "favoriteCount": self.favorite_count,
            "createdAt": self.created_at.isoformat() if self.created_at else None,
            "updatedAt": self.updated_at.isoformat() if self.updated_at else None,
        }


class TimeSlotStatus(str, enum.Enum):
    """时段状态"""
    AVAILABLE = "available"
    BOOKED = "booked"
    MATCH = "match"  # 散客场


class TimeSlot(Base):
    """时段表"""
    __tablename__ = "time_slots"
    
    id = Column(String(36), primary_key=True, index=True)
    venue_id = Column(String(36), nullable=False, index=True)
    date = Column(String(10), nullable=False, index=True)  # YYYY-MM-DD
    start_time = Column(String(5), nullable=False)  # HH:mm
    end_time = Column(String(5), nullable=False)  # HH:mm
    price = Column(Float, nullable=False)
    status = Column(SQLEnum(TimeSlotStatus), default=TimeSlotStatus.AVAILABLE)
    
    # 散客场信息
    current_players = Column(Integer, default=0)
    max_players = Column(Integer, default=0)
    
    # 关联订单
    booking_id = Column(String(36))
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "venueId": self.venue_id,
            "date": self.date,
            "startTime": self.start_time,
            "endTime": self.end_time,
            "price": self.price,
            "status": self.status,
            "currentPlayers": self.current_players,
            "maxPlayers": self.max_players,
            "bookingId": self.booking_id
        }

